 <template>
    <div>
        <el-row>
            <!--检索-->
            <el-form :inline="true" :model="searchParam" class="demo-form-inline">
                <el-col :span="3">&nbsp;</el-col>
                <el-col :span="3"><el-input v-model="searchParam.userName" size="mini" placeholder="请输入登录名"></el-input></el-col>
                <el-col :span="3"><el-input v-model="searchParam.loginName" size="mini" placeholder="请输入用户名"></el-input></el-col>
                <el-col :span="3"><el-input v-model="searchParam.email" size="mini" placeholder="请输入邮箱"></el-input></el-col>
                <el-col :span="3"><el-input v-model="searchParam.phoneNumber" size="mini" placeholder="请输入电话"></el-input></el-col>
                <el-col :span="3"><el-button type="primary" size="mini" @click="search()" icon="el-icon-search">搜索</el-button></el-col>
            </el-form>
            <el-col :span="3"><el-button type="primary" size="mini" @click="flush()" icon="el-icon-search">刷新</el-button></el-col>

            <el-col :span="3"
                ><el-button type="primary" size="mini" @click="addFormVisible = true" icon="el-icon-circle-plus">添加</el-button></el-col
            >
        </el-row>

        <el-row>
            <!-- 表格展示 -->
            <el-table :data="tableData" style="width: 100%">
                <el-table-column type="index" label="#" sortable> </el-table-column>
                <el-table-column prop="userName" label="用户名"> </el-table-column>
                <el-table-column prop="loginName" label="名字"> </el-table-column>
                <el-table-column prop="user_type" :formatter="getTypeName" label="用户类型"> </el-table-column>
                <el-table-column prop="email" label="邮箱"> </el-table-column>
                <el-table-column prop="phonenumber" label="电话"> </el-table-column>
                <el-table-column prop="sex" :formatter="getSexName" label="性别"> </el-table-column>
                <el-table-column label="头像">
                    　<template slot-scope="scope">
                        <el-image style="width: 50px; height: 50px" :src="scope.row.avatar"></el-image>
                    </template>
                    <!--<img :src="avatar" class="userAvatar"
                             style="display: block;width: 50px;height: 50px;
                         border-radius: 50%;-webkit-border-radius: 50%;
                         -moz-border-radius: 50%;
                         border: 4px solid #44576b;box-sizing: border-box;margin: 10px auto 10px;">-->
                </el-table-column>
                <el-table-column prop="status" :formatter="getStatusName" label="状态"> </el-table-column>
                <el-table-column prop="loginIp" label="登录IP"> </el-table-column>
                <el-table-column prop="loginDate" label="最后一次登录时间"> </el-table-column>
                <el-table-column label="操作" width="240px">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="toShowRoles(scope.$index, scope.row)">赋予角色</el-button>
                        <el-button size="mini" @click="toEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!-- 分页 -->
        <el-row>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.pageNo"
                :page-sizes="[5, 10, 100, 200]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
            >
            </el-pagination>
        </el-row>
        <el-row>
            <!--添加弹出框-->
            <el-dialog title="添加" :visible.sync="addFormVisible">
                <el-form :model="addForm">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="addForm.userName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="addForm.loginName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" :label-width="formLabelWidth">
                        <el-radio v-model="addForm.userType" label="0">管理员</el-radio>
                        <el-radio v-model="addForm.userType" label="1">代理商</el-radio>
                        <el-radio v-model="addForm.userType" label="2">商户</el-radio>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth">
                        <el-input v-model="addForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth">
                        <el-input v-model="addForm.phonenumber" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-radio v-model="addForm.sex" label="0">男</el-radio>
                        <el-radio v-model="addForm.sex" label="1">女</el-radio>
                        <el-radio v-model="addForm.sex" label="2">未知</el-radio>
                    </el-form-item>
                    <el-form-item label="头像上传" :label-width="formLabelWidth">
                        <!--图片上传-->
                        <el-upload
                            class="avatar-uploader"
                            action="http://192.168.1.72:8888/commonOSS/upload"
                            name="file"
                            :auto-upload="true"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="addForm.password" autocomplete="off" show-password></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
        <el-row>
            <!--更新弹出框-->
            <el-dialog title="更新" :visible.sync="updateFormVisible">
                <el-form :model="updateForm">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="updateForm.userName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="名称" :label-width="formLabelWidth">
                        <el-input v-model="updateForm.loginName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" :label-width="formLabelWidth">
                        <el-radio v-model="updateForm.userType" :label="0">管理员</el-radio>
                        <el-radio v-model="updateForm.userType" :label="1">代理商</el-radio>
                        <el-radio v-model="updateForm.userType" :label="2">商户</el-radio>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth">
                        <el-input v-model="updateForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth">
                        <el-input v-model="updateForm.phonenumber" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-radio v-model="updateForm.sex" :label="0">男</el-radio>
                        <el-radio v-model="updateForm.sex" :label="1">女</el-radio>
                        <el-radio v-model="updateForm.sex" :label="2">未知</el-radio>
                    </el-form-item>
                    <el-form-item label="头像" :label-width="formLabelWidth">
                        <el-image
                            v-if="updateForm.avatar == '' || updateForm.avatar == null ? false : true"
                            style="width: 100px; height: 100px"
                            :src="updateForm.avatar"
                        ></el-image>
                        <el-upload
                            class="avatar-uploader"
                            action="http://192.168.1.72:8888/commonOSS/upload"
                            name="file"
                            :auto-upload="true"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth">
                        <el-input v-model="updateForm.password" autocomplete="off" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-radio v-model="updateForm.status" :label="0">正常</el-radio>
                        <el-radio v-model="updateForm.status" :label="1">禁用</el-radio>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="updateFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="update()">确 定</el-button>
                </div>
            </el-dialog>
            <!--角色授权弹出框-->
            <el-dialog title="角色列表" :visible.sync="rolesVisible">
                <template>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0"></div>
                    <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                        <el-checkbox v-for="role in roles" :label="role.roleId" :key="role.roleId">{{ role.roleName }}</el-checkbox>
                    </el-checkbox-group>
                </template>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addUserAndRole()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
    </div>
</template>

<script>
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
Vue.use(VueAxios, axios);

export default {
    data() {
        return {
            searchParam: { pageNo: 1, pageSize: 5 },
            //数据
            tableData: [],
            page: {},
            roleName: null,
            addFormVisible: false, //添加对话框是否显示
            updateFormVisible: false, //更新对话框是否显示
            addForm: { userType: '0', sex: '0', status: '0' }, //添加
            updateForm: {}, //更新form
            formLabelWidth: '120px',
            roleId: 0, //角色id

            rolesVisible: false, //角色列表弹出框
            //用户关联角色相关的
            checkAll: false,
            checkedRoles: [],
            roles: [],
            isIndeterminate: true,
            roleIds: '',
            userId: 0,
            imageUrl: ''
        };
    },
    created: function () {
        var _this = this;
        _this.loadData();
        //初始化数据，加载所有的角色
        axios
            .get('http://192.168.1.72:9999/prs/role/queryAllByParam', {
                params: {
                    pageNo: 1,
                    pageSize: 1000
                }
            })
            .then(function (response) {
                _this.roles = response.data.data.list;
            });
    },
    methods: {
        //方法
        //加载数据的方法
        loadData: function () {
            var _this = this;
            //初始化数据
            axios
                .get('http://192.168.1.72:9999/prs/user/queryAll', {
                    params: {
                        pageNo: this.searchParam.pageNo,
                        pageSize: this.searchParam.pageSize,
                        loginName: this.searchParam.loginName,
                        userName: this.searchParam.userName,
                        email: this.searchParam.email,
                        phoneNumber: this.searchParam.phoneNumber
                    }
                })
                .then(function (response) {
                    //赋值分页列表
                    _this.tableData = response.data.data.list;
                    _this.page = response.data.data;
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        //每页数量发生变化时
        handleSizeChange: function (v) {
            this.searchParam.pageSize = v;
            this.loadData();
        },
        //当前页数放生变化是
        handleCurrentChange: function (v) {
            this.searchParam.pageNo = v;
            this.loadData();
        },
        // 搜索方法
        search: function () {
            this.pageNo = 1;
            this.loadData();
        },
        //跳转更新
        toEdit: function (index, row) {
            var _this = this;
            //清空原来的
            _this.updateForm.avatar = '';
            _this.updateForm = row;
            _this.updateFormVisible = true;
        },
        //弹出角色选择对话框
        toShowRoles: function (index, row) {
            var _this = this;
            _this.userId = row.userId;
            //根据当前用户ID查询对应的所有角色id集合 赋值给默认选中checkedRoles
            //初始化数据，加载所有的角色
            axios.get('http://192.168.1.72:9999/prs/user/selectRoleIdsByUserId?userId=' + row.userId).then(function (response) {
                _this.checkedRoles = response.data.data;
            });
            _this.rolesVisible = true;
        },
        //添加用户和角色关联方法
        addUserAndRole() {
            var _this = this;
            console.log('roleIds:' + this.roleIds);
            if (this.roleIds.length < 1) {
                _this.$message.error('至少选中一个角色。。。');
                return;
            }
            //调用后台方法，添加数据库
            axios
                .post('http://192.168.1.72:9999/prs/user/addUserAndRole?userId=' + this.userId + '&roleIds=' + this.roleIds)
                .then(function (response) {
                    console.log(response);
                    if (response.status == 200) {
                        if (response.data > 0) {
                            //提示成功
                            _this.$message({
                                type: 'success',
                                message: '添加成功!'
                            });
                            //关闭弹框
                            _this.rolesVisible = false;
                            //重新加载数据
                            _this.loadData();
                        }
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    _this.$message.error('你错了。。。');
                });
        },
        //删除
        handleDelete: function (index, row) {
            var _this = this;
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    axios
                        .delete('http://192.168.1.72:9999/prs/user/deleteById?userId=' + row.userId)
                        .then(function (response) {
                            console.log(response);
                            if (response.status == 200) {
                                if (response.data > 0) {
                                    //提示成功
                                    _this.$message({
                                        type: 'success',
                                        message: '删除成功!'
                                    });
                                    //重新加载数据
                                    _this.loadData();
                                }
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            _this.$message.error('你错了。。。');
                        });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
        },
        //添加
        add: function () {
            var _this = this;
            axios
                .post('http://192.168.1.72:9999/prs/user/insert', _this.addForm)
                .then(function (response) {
                    console.log(response);
                    if (response.status == 200) {
                        //提示成功
                        _this.$message({
                            message: '恭喜你，添加成功',
                            type: 'success'
                        });
                        //_this.$message.success("恭喜你，添加成功");
                        //关闭弹出框
                        _this.addFormVisible = false;
                        //重新加载数据
                        _this.loadData();
                        //清空form
                        _this.addForm = {};
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    _this.$message.error('你错了。。。');
                });
        },
        //更新
        update: function () {
            //JSON.stringify JSON 转 String
            // alert(JSON.stringify(this.form));
            var _this = this;
            axios
                .put('http://192.168.1.72:9999/prs/user/update', this.updateForm)
                .then(function (response) {
                    console.log(response);
                    if (response.status == 200) {
                        //提示成功
                        _this.$message({
                            message: '恭喜你，操作成功',
                            type: 'success'
                        });
                        //_this.$message.success("恭喜你，添加成功");
                        //关闭弹出框
                        _this.updateFormVisible = false;
                        //重新加载数据
                        _this.loadData();
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    _this.$message.error('你错了。。。');
                });
        },
        //用户类型获取名称
        getTypeName(row, column, cellValue) {
            // return cellValue==0?'后台管理员':cellValue==1?"代理商":"商户";
            var tmpType = '';
            if (cellValue == 0) {
                tmpType = '管理员';
            } else if (cellValue == 1) {
                tmpType = '代理商';
            } else {
                tmpType = '商户';
            }
            return tmpType;
        },
        //用户性别
        getSexName(row, column, cellValue) {
            return cellValue == 0 ? '男' : cellValue == 1 ? '女' : '未知';
            /* var tmpType = "";
                     if (cellValue == 0) {
                         tmpType = "后台管理员";
                     } else if (cellValue == 1) {
                         tmpType = "代理商";
                     } else {
                         tmpType = "商户";
                     }
                     return tmpType;*/
        },
        //账户状态名字
        getStatusName(row, column, cellValue) {
            return cellValue == 0 ? '正常' : '禁用';
        },
        //处理全选改变
        handleCheckAllChange(val) {
            //console.log("。。。。"+val);
            if (val) {
                //判断是否为true
                for (var i = 0; i < this.roles.length; i++) {
                    this.checkedRoles.push(this.roles[i].roleId);
                }
            } else {
                this.checkedRoles = [];
            }
            //this.checkedRoles = val ? this.roles : [];
            this.isIndeterminate = false;
        },
        handleCheckedRolesChange(value) {
            console.log('选中的：' + value);
            this.roleIds = value;
            let checkedCount = value.length;

            this.checkAll = checkedCount === this.roles.length; //=== 数据类和数据都要匹配
            //== 数据匹配
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
        },
        flush() {
            //刷新当前页
            location.reload();
        },
        //图片上传成功后
        handleAvatarSuccess: function (res, file) {
            var _this = this;
            //图片回显
            _this.imageUrl = URL.createObjectURL(file.raw);
            //   alert(file.response);
            // alert(JSON.stringify(file.response));
            _this.addForm.avatar = file.response.ossFileUrlBoot;
            _this.updateForm.avatar = file.response.ossFileUrlBoot;
            console.log('ossFileUrlBoot:' + file.response.ossFileUrlBoot);
            console.log('updateForm:' + _this.updateForm.avatar + ':addForm:' + _this.addForm.avatar);
            // this.form.fileName=file.response.oldFileName;
            // this.form.filePath=file.response.newFilePath;
        },
        //上传前图片类型和大小判断
        beforeAvatarUpload: function (file) {
            // const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 5;
            /* if (!isJPG) {
                          this.$message.error('上传头像图片只能是 JPG 格式!');
                      }*/
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isLt2M;
        }
    }
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}
.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>